﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Collections;
using System.IO;
using EAGetMail;
using Business;
using System.Data;
using System.Text;

public partial class client_Oil_Report : System.Web.UI.Page
{
    private string m_uidlfile = "uidl.txt";
    private string m_curpath = "";
    private string sampleID;
    private string status;
    private string uin;
    private ArrayList m_arUidl = new ArrayList();
    protected void Page_Load(object sender, EventArgs e)
    {
        ListMail();
        string tempFolder = String.Format("{0}\\inbox", Server.MapPath(""));
        m_curpath = tempFolder;
        RetrieveEmail();
        ListMail();

    }
    private void ListMail()
    {
        string tempFolder = String.Format("{0}\\inbox", Server.MapPath(""));
        m_curpath = tempFolder;
        string mailFolder = String.Format("{0}", m_curpath);
        if (!System.IO.Directory.Exists(mailFolder))
            Directory.CreateDirectory(mailFolder);

        tbMail.Rows.Clear();

        TableRow row = new TableRow();
        TableCell cel = new TableCell();
        cel.Text = "<b>From</b>";
        row.Cells.Add(cel);

        cel = new TableCell();
        cel.Text = "<b>Subject</b>";
        row.Cells.Add(cel);

        cel = new TableCell();
        cel.Text = "<b>Date</b>";
        row.Cells.Add(cel);

        cel = new TableCell();
        cel.Text = "<b>&nbsp;</b>";
        row.Cells.Add(cel);

        tbMail.Rows.Add(row);

        string[] files = Directory.GetFiles(mailFolder, "*.eml");
        int count = files.Length;
        for (int i = 0; i < count; i++)
        {
            string fullname = files[i];
            //For evaluation usage, please use "TryIt" as the license code, otherwise the 
            //"invalid license code" exception will be thrown. However, the object will expire in 1-2 months, then
            //"trial version expired" exception will be thrown.
            Mail oMail = new Mail("TryIt");
            oMail.Load(fullname, true);
            row = new TableRow();
            cel = new TableCell();
            string s = Server.HtmlEncode(oMail.From.ToString());
            if (s.Length == 0)
                s = "[no sender]";

            s = String.Format("<a href=\"display.aspx?name={0}\" onclick=\"javascript:fnDisplay( this.href );return false;\">{1}</a>",
                Server.UrlEncode(fullname), s);//fullname:  C:\\Users\\TonyXU\\Documents\\Visual Studio 2008\\Projects\\mypeojects\\i2iPortal\\Presentation\\client\\inbox\\201102151011285620.eml

            cel.Text = s;
            row.Cells.Add(cel);

            cel = new TableCell();
            cel.Text = Server.HtmlEncode(oMail.Subject);
            //subject:
            //oMail.Subject = "[ALERT] [ID:19843657-43316] [BBS Millme][MM0EAF10AF][Gearbox Ch][733031100][Abnormal] (Trial Version)"
            string subject = cel.Text.Replace(" ", "");
            string[] sArray = subject.Split(new char[2] { '[', ']' });
            string[] samplearray = new string[10];
            int m = 0;
            foreach (string str in sArray)
            {
                string getparts = str.ToString();
                if (getparts != "" && getparts != "ALERT" && getparts != " ")
                {
                    samplearray[m] = getparts;
                    m++;
                }

            }
            row.Cells.Add(cel);

            cel = new TableCell();
            cel.Text = oMail.ReceivedDate.ToString("yyyy-MM-dd HH:mm:ss");
            row.Cells.Add(cel);

            s = String.Format("<a href=\"delete.aspx?name={0}\">Delete</a>",
                Server.UrlEncode(fullname));

            cel = new TableCell();
            cel.Text = s;
            row.Cells.Add(cel);

            tbMail.Rows.Add(row);
            // Load( file, true ) only load the email header to Mail object to save the CPU and memory
            // the Mail object will load the whole email file later automatically if bodytext or attachment is required..
            oMail.Load(fullname, true);
            string uin = getUIN(fullname);
            string sampleddate = getSampledate(fullname);

            if (uin != "")
            {
                samplearray[7] = uin;//0:  "ID:19843657-43316" 1:"BBSMillme" 2:"MM0EAF10AF" 3:"GearboxCh" 4: "733031100" 5:"Abnormal" 6:"(TrialVersion)" 7:"MM0EAF10AF001MG2"
            }
            string[] sampleInfo = new string[3];
            string attachmentlink = getAttachmentLink(fullname);
            if (attachmentlink != "")
            {
                samplearray[8] = attachmentlink;
            }

            if (sampleddate != "")
            {
                samplearray[9] = sampleddate;
            }
            //sampleInfo[0]=samplearray[];
            MatchSample(samplearray);
            oMail.Clear();
        }
    }
    private void MatchSample(string[] sampleInfo)
    {
        sampleID = sampleInfo[4];
        string uinNO = sampleInfo[7];
        status = sampleInfo[5];
        string attachmentlink = sampleInfo[8];
        string sampledate = sampleInfo[9];
        string select_query = "SELECT * FROM OilReports WHERE sample_id='" + sampleID + "' and status is null";
        CreateConn objcon = new CreateConn();
        DataTable dt = objcon.SQLConnDataTable(select_query);
        if (dt != null && dt.Rows.Count > 0)
        {
            try
            {
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        string id = dr["id"].ToString();
                        String modify_query = "Update OilReports set reportlink='" + attachmentlink + "',status='" + status + "' WHERE id='" + id + "'";
                        CreateConn objcon_modify = new CreateConn();
                        objcon_modify.SQLConnDataTable(modify_query);
                        string update_UIN = "Update ComponentTechnicalData set Value='" + uinNO + "' WHERE Attribute='UIN' or Attribute='uin' and Component_id IN (SELECT Component_id FROM OilReports WHERE id='" + id + "')";
                        CreateConn objcon2 = new CreateConn();
                        objcon2.SQLConnDataTable(update_UIN);
                    }
                }
            }
            catch (Exception e)
            {
                String Errmsg = e.ToString();
            }

        }
        else
        {
            string query2 = "SELECT * FROM OilReports WHERE machine_id in (SELECT machine_id FROM Machines WHERE uin='" + uinNO + "') and tested_date=convert(datetime,'" + sampledate + "',103)";
            CreateConn objcon2 = new CreateConn();
            try
            {
                DataTable dt2 = objcon2.SQLConnDataTable(query2);
                if (dt2 != null && dt2.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt2.Rows)
                    {
                        string id = dr["id"].ToString();
                        String modify_query = "Update OilReports set reportlink='" + attachmentlink + "',status='" + status + "'";
                        CreateConn objcon_modify = new CreateConn();
                        objcon_modify.SQLConnDataTable(modify_query);
                    }
                }
            }
            catch (Exception e)
            {
                String Errmsg = e.ToString();
            }

        }


    }
    private string getAttachmentLink(string emlFile)
    {
        Mail oMail = new Mail("TryIt");
        oMail.Load(emlFile, false);
        string attname = "";
        Attachment[] atts = oMail.Attachments;
        int count = atts.Length;
        if (count > 0)
        {
            for (int i = 0; i < count; i++)
            {
                Attachment att = atts[i];

                attname = String.Format("attachment.aspx?name={0}&seq={1}", Server.UrlEncode(emlFile), i);

                if (att.Name.IndexOf("pdf") != -1)
                {
                    return attname;

                }

            }
        }
        return attname;
    }
    private string getUIN(string emlFile)
    {
        Mail oMail = new Mail("TryIt");
        oMail.Load(emlFile, false);

        string html = oMail.HtmlBody;
        string uin = "";
        //int startindex = html.IndexOf("Unit ID:");
        int startindex = html.IndexOf("Compartment UIN:");
        int htmllength = html.Length;
        //int endindex = html.IndexOf("Site");
        try
        {
            string uin_pre = html.Substring(startindex + 16, 30);

            string uin_2 = uin_pre.Replace(" ", "");
            int endindex2 = uin_2.IndexOf('\r');
            string uin_result = uin_2.Substring(0, endindex2);
            uin = uin_result;
            //uin_2 = uin_pre.Replace(" ", ""); //"UnitID:MM0EAF10AF001MG2\r\n<br>&gt;"  "M0EAF10AF001MG2" "MM0EAF10AF001MG2"
            //int endindex2 = uin_2.IndexOf('\r');
            //uin = uin_2.Substring(15, endindex2 - 15);
        }
        catch (Exception e)
        {
            String ErrMsg = e.ToString();
        }
        return uin;
    }
    private string getSampledate(string emlFile)
    {
        Mail oMail = new Mail("TryIt");
        oMail.Load(emlFile, false);

        string html = oMail.HtmlBody;
        string uin = "";
        int startindex = html.IndexOf("Date sampled:");
        int htmllength = html.Length;
        int endindex = html.IndexOf("Severity");
        try
        {
            string uin_pre = html.Substring(startindex, endindex - startindex);
            string uin_2;
            uin_2 = uin_pre.Replace(" ", ""); //"UnitID:MM0EAF10AF001MG2\r\n<br>&gt;"  "M0EAF10AF001MG2" "MM0EAF10AF001MG2"
            int endindex2 = uin_2.IndexOf('\r');
            uin = uin_2.Substring(12, endindex2 - 12);
        }
        catch (Exception e)
        {
            String ErrMsg = e.ToString();
        }
        return uin;//"11/01/2011"
    }
    private void RetrieveEmail()
    {
        MailServer oServer = new MailServer("mail.i2iportal.com.au",
            "oil@i2iportal.com.au", "wk733567d", true,
            ServerAuthType.AuthLogin, ServerProtocol.Pop3);



        MailClient oClient = new MailClient("TryIt");
        bool bLeaveCopy = true;
        try
        {
            // uidl is the identifier of every email on POP3/IMAP4 server, to avoid retrieve
            // the same email from server more than once, we record the email uidl retrieved every time
            // if you delete the email from server every time and not to leave a copy of email on
            // the server, then please remove all the function about uidl.
            _LoadUIDL();

            string mailFolder = String.Format("{0}", m_curpath);
            if (!Directory.Exists(mailFolder))
                Directory.CreateDirectory(mailFolder);

            oClient.Connect(oServer);
            MailInfo[] infos = oClient.GetMailInfos();
            TotalEmailLabel.Text = "Total " + infos.Length + " email(s)";

            _SyncUIDL(oServer, infos);
            int count = infos.Length;

            for (int i = 0; i < count; i++)
            {
                MailInfo info = infos[i];
                if (_FindExistedUIDL(oServer, info.UIDL))
                {
                    //this email has existed on local disk.
                    continue;
                }

                //lblStatus.Text = String.Format( "Retrieving {0}/{1}...", info.Index, count );

                Mail oMail = oClient.GetMail(info);
                System.DateTime d = System.DateTime.Now;
                System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US");
                string sdate = d.ToString("yyyyMMddHHmmss", cur);
                string fileName = String.Format("{0}\\{1}{2}{3}.eml", mailFolder, sdate, d.Millisecond.ToString("d3"), i);
                oMail.SaveAs(fileName, true);


                if (bLeaveCopy)
                {
                    //add the email uidl to uidl file to avoid we retrieve it next time. 
                    _AddUIDL(oServer, info.UIDL);
                }
            }

            if (!bLeaveCopy)
            {
                //lblStatus.Text = "Deleting ...";
                for (int i = 0; i < count; i++)
                    oClient.Delete(infos[i]);
            }
            // Delete method just mark the email as deleted, 
            // Quit method pure the emails from server exactly.
            oClient.Quit();
            CompletedLabel.Text = "Completed!";

        }
        catch (Exception ep)
        {
            CompletedLabel.Text = ep.Message;
        }

        //update the uidl list to a text file and then we can load it next time.
        _UpdateUIDL();
    }

    // uidl is the identifier of every email on POP3/IMAP4 server, to avoid retrieve
    // the same email from server more than once, we record the email uidl retrieved every time
    // if you delete the email from server every time and not to leave a copy of email on
    // the server, then please remove all the function about uidl.

    private bool _FindUIDL(MailInfo[] infos, string uidl)
    {
        int count = infos.Length;
        for (int i = 0; i < count; i++)
        {
            if (String.Compare(infos[i].UIDL, uidl, true) == 0)
                return true;
        }
        return false;
    }

    //remove the local uidl which is not existed on the server.
    private void _SyncUIDL(MailServer oServer, MailInfo[] infos)
    {
        string s = String.Format("{0}#{1} ", oServer.Server, oServer.User);

        bool bcontinue = false;
        int n = 0;
        do
        {
            bcontinue = false;
            int count = m_arUidl.Count;
            for (int i = n; i < count; i++)
            {
                string x = m_arUidl[i] as string;
                if (String.Compare(s, 0, x, 0, s.Length, true) == 0)
                {
                    int pos = x.LastIndexOf(' ');
                    if (pos != -1)
                    {
                        string uidl = x.Substring(pos + 1);
                        if (!_FindUIDL(infos, uidl))
                        {
                            //this uidl doesn't exist on server, 
                            //so we should remove it from local uidl list to save the storage.
                            bcontinue = true;
                            n = i;
                            m_arUidl.RemoveAt(i);
                            break;
                        }
                    }
                }
            }
        } while (bcontinue);

    }

    private bool _FindExistedUIDL(MailServer oServer, string uidl)
    {
        string s = String.Format("{0}#{1} {2}", oServer.Server, oServer.User, uidl);
        int count = m_arUidl.Count;
        for (int i = 0; i < count; i++)
        {
            string x = m_arUidl[i] as string;
            if (String.Compare(s, x, true) == 0)
                return true;
        }
        return false;
    }

    private void _AddUIDL(MailServer oServer, string uidl)
    {
        string s = String.Format("{0}#{1} {2}", oServer.Server, oServer.User, uidl);
        m_arUidl.Add(s);
    }

    private void _UpdateUIDL()
    {
        StringBuilder s = new StringBuilder();
        int count = m_arUidl.Count;
        for (int i = 0; i < count; i++)
        {
            s.Append(m_arUidl[i] as string);
            s.Append("\r\n");
        }

        string file = String.Format("{0}\\{1}", m_curpath, m_uidlfile);

        FileStream fs = null;
        try
        {
            fs = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None);
            byte[] data = System.Text.Encoding.Default.GetBytes(s.ToString());
            fs.Write(data, 0, data.Length);
            fs.Close();
        }
        catch (Exception ep)
        {
            if (fs != null)
                fs.Close();

            throw ep;
        }

    }

    private void _LoadUIDL()
    {
        m_arUidl.Clear();
        string file = String.Format("{0}\\{1}", m_curpath, m_uidlfile);
        StreamReader read = null;
        try
        {
            read = File.OpenText(file);
            while (true)
            {
                string line = read.ReadLine().Trim("\r\n \t".ToCharArray());
                m_arUidl.Add(line);
            }
        }
        catch (Exception)
        { }

        if (read != null)
            read.Close();
    }

    protected void LoginStatus1_LoggingOut(object sender, LoginCancelEventArgs e)
    {
        Session.Abandon();
        Session.Contents.RemoveAll();
        FormsAuthentication.SignOut();
    }
}
